const $ = layui.jquery;
const form = layui.form;
const layer = layui.layer;
const upload = layui.upload;
const dropdown = layui.dropdown;
const tree = layui.tree;

$(() => {
    //渲染图片上传
    upload.render({
        elem: '#pic-upload-btn',
        url: ctx + '/sys/api/v1/upload/image',
        //field: "file",
        //dataType: "json",
        data: {
            type: "goods_pics"
        },
        exts: "jpg|png|gif|jpeg|bmp",
        size: 1024,//单位kb
        text: {
            error: "上传失败"
        },
        done: function (resp) {
            if (resp.success) {
                let url =ctx+"/assets/"+resp.data;
                $(".pic-upload-preview").css("background-image", "url(" + url + ")");
                sessionStorage.setItem("pic-url", resp.data);
            }
        },
        error: function (resp) {
            console.log(resp);
        }
    });
    //渲染副图片上传
    upload.render({
        elem: '#pic1-upload-btn',
        url: ctx + '/sys/api/v1/upload/image',
        //field: "file",
        //dataType: "json",
        data: {
            type: "goods_pics"
        },
        exts: "jpg|png|gif|jpeg|bmp",
        size: 1024,//单位kb
        text: {
            error: "上传失败"
        },
        done: function (resp) {
            if (resp.success) {
                $(".pic1-upload-preview").css("background-image", "url(" + (ctx + "/assets/" + resp.data) + ")");
                sessionStorage.setItem("pic1-url", resp.data);
            }
        },
        error: function (resp) {
            console.log(resp);
        }
    });

    //细节图多图上传，本质上是每次上传一幅，上传多次
    upload.render({
        elem: '#pics-upload-btn',
        url: ctx + '/sys/api/v1/upload/image',
        data: {
            type: "goods_pics"
        },
        multiple: true,
        exts: "jpg|png|gif|jpeg|bmp",
        size: 1024,//单位kb
        text: {
            error: "上传失败"
        },
        done: function (resp) {
            if (resp.success) {
                let url = ctx + "/assets/" + resp.data;
                let $img = $("<div class='goods-pics'><i>删除</i></div>").css("background-image", "url(" + (url) + ")").data("url", resp.data);
                $("#pics-upload-preview").append($img);
            }
        },
        error: function (resp) {
            console.log(resp);
        }
    });

    //多图删除
    $("#pics-upload-preview").on("click", ".goods-pics > i", function () {
        let $img = $(this).closest(".goods-pics");
        $img.remove();
    });

    //填充品牌
    fillBrand();
    //填充类别
    fillCategory();

    //渲染富文本编辑器
    let ue = UE.getEditor('editor', {
        serverUrl: ctx + "/sys/api/v1/ue",
        toolbars: [
            [
                "fullscreen",   // 全屏
                "source",       // 源代码
                "|",
                "undo",         // 撤销
                "redo",         // 重做
                "|",
                "bold",         // 加粗
                "italic",       // 斜体
                "underline",    // 下划线
                "strikethrough",// 删除线
                "superscript",  // 上标
                "subscript",    // 下标
                "removeformat", // 清除格式
                "formatmatch",  // 格式刷
                "|",
                "forecolor",    // 字体颜色
                "backcolor",    // 背景色
                "insertorderedlist",   // 有序列表
                "insertunorderedlist", // 无序列表
                "selectall",    // 全选
                "cleardoc",     // 清空文档
                "|",
                "rowspacingtop",// 段前距
                "rowspacingbottom",    // 段后距
                "lineheight",          // 行间距
                "|",
                "customstyle",         // 自定义标题
                "paragraph",           // 段落格式
                "fontfamily",          // 字体
                "fontsize",            // 字号
                "|",
                "justifyleft",         // 居左对齐
                "justifycenter",       // 居中对齐
                "justifyright",
                "justifyjustify",      // 两端对齐
                "|",
                "link",                // 超链接
                "unlink",              // 取消链接
                "anchor",              // 锚点
                "|",
                "imagenone",           // 图片默认
                "imageleft",           // 图片左浮动
                "imageright",          // 图片右浮动
                "imagecenter",         // 图片居中
                "|",
                "simpleupload",        // 单图上传
            ]
        ]
    });
    window.ue = ue;

    // 数据回显
    displayGoods();


});

//手动提交表单，表单校验也需要手动，在此方法中，也可以调用form.submit("xxx",function(data){});
function doSubmit(cb) {
    const url = ctx + "/sys/api/v1/goods";
    let pic = sessionStorage.getItem("pic-url");
    let pic1 = sessionStorage.getItem("pic1-url");
    const formData = form.val("form");
    if (pic) {
        formData.pic = pic;//商品主图
    }

    if (pic1) {
        formData.pic1 = pic1;//商品主图
    }

    let otherPics = [];
    $("#pics-upload-preview>.goods-pics").each(function () {
        let url = $(this).data("url");
        if (url) {
            otherPics.push(url);
        }
    });
    formData.otherPics = otherPics;
    formData.id = window.goods.id;//修改时，必须有id
    formData.detail = window.ue.getContent();//获取富文本编辑器内容

    //console.log(formData);

    //验证整个表单
    let pass = form.validate("#form");
    if (!pass) {
        return;//验证不通过，则返回
    }

    $.ajax({
        url,
        method: "put",
        dateType: "json",
        data: formData,
        success(resp) {
            if (typeof cb === "function") {
                cb(resp.success);
            }
        },
        error(resp) {
            let json = resp.responseJSON;
            layer.msg(json.msg || "修改商品失败");
        }
    })
}


//填充品牌下拉列表框
function fillBrand() {
    const url = ctx + "/sys/api/v1/brand/all";
    $.ajax({
        url,
        method: "get",
        dataType: "json",
        success(resp) {
            if (resp.success) {
                let rows = resp.data;
                let $brand = $("[name=brandId]");
                $brand.append("<option value=''>不限</option>");
                for (let row of rows) {
                    $brand.append("<option value='" + row.id + "'>" + row.name + "</option>");
                }
                form.render("select", "form");
            }
        }
    });
}

//填充类别
function fillCategory() {
    //查询类别树
    const url = ctx + "/sys/api/v1/category";
    $.ajax({
        url,
        method: "get",
        dataType: "json",
        success(resp) {
            if (resp.success) {
                let treeData = resp.data;

                //实例化下拉框
                dropdown.render({
                    id: "category-dropdown",
                    elem: "[name=categoryName]",
                    content: "<div id='category-tree' style='min-width: 300px;height: 300px;overflow-y: scroll'></div>",
                    //每次展开下拉面板都会触发，由于每次关闭面板后，整个dom会被移除，且不打开面板时，是不会创建dom的
                    //所有tree的渲染必须放在ready函数中
                    ready() {
                        tree.render({
                            elem: "#category-tree",
                            data: treeData,
                            customName: {
                                title: "name"
                            },
                            onlyIconControl: true,//仅能通过点击节点前图标控制收缩和展开
                            click(obj) {
                                let node = obj.data;//节点数据
                                $("[name=categoryName]").val(node.name);
                                $("[name=categoryId]").val(node.id);
                                //关闭下拉面板，参数为下拉实例的id
                                dropdown.close("category-dropdown");
                            }
                        });
                    }
                });
            }
        }
    });
}

//表单回显商品数据
function displayGoods() {
    const url = ctx + "/sys/api/v1/goods/id";
    $.ajax({
        url,
        method: "get",
        data: {
            id
        },
        success(resp) {
            if (resp.success) {
                let goods = resp.data;
                form.val("form", goods);

                //类别赋值
                if(goods.category){
                    $("[name=categoryName]").val(goods.category.name);
                    $("[name=categoryId]").val(goods.category.id);
                }

                //回显商品图片
                if (goods.pic) {
                    $(".pic-upload-preview").css("background-image", "url(" + (ctx + "/assets/" + goods.pic) + ")");
                    sessionStorage.setItem("pic-url", goods.pic);
                }
                //回显商品副图片
                if (goods.pic1) {
                    $(".pic1-upload-preview").css("background-image", "url(" + (ctx + "/assets/" + goods.pic1) + ")");
                    sessionStorage.setItem("pic1-url", goods.pic1);
                }
                //回显细节图片
                if (goods.otherPics.length > 0) {
                    for (let pic of goods.otherPics) {
                        if(pic){
                            let url = ctx + "/assets/" + pic;
                            let $img = $("<div class='goods-pics'><i>删除</i></div>").css("background-image", "url(" + (url) + ")").data("url", pic);
                            $("#pics-upload-preview").append($img);
                        }

                    }
                }

                window.goods = goods;

                //回显富文本。就绪之后执行的函数
                window.ue.ready(() => {
                    if (goods.detail) {
                        window.ue.setContent(goods.detail);
                    }
                });


            }
        }
    });
}